package com.pengshun.modules.api.user.service.impl;

import com.pengshun.modules.aliyun.OosPush;
import com.pengshun.modules.api.coal.repository.MerchantRepository;
import com.pengshun.modules.api.coal.service.dto.MerchantDto;
import com.pengshun.modules.api.coal.service.mapstruct.MerchantMapper;
import com.pengshun.modules.api.huanxin.service.HuanXinService;
import com.pengshun.modules.api.mapper.PsUserInfoMapper;
import com.pengshun.modules.api.mapper.SystemMapper;
import com.pengshun.modules.api.system.service.dto.AddresDto;
import com.pengshun.modules.api.user.repository.*;
import com.pengshun.modules.api.user.service.dto.UserCenter;
import com.pengshun.modules.api.coal.repository.UserRepository;
import com.pengshun.modules.api.coal.service.dto.UserDto;
import com.pengshun.modules.api.coal.service.mapstruct.UserMapper;
import com.pengshun.modules.api.coal.util.SystemPath;
import com.pengshun.modules.api.user.para.UserPara;
import com.pengshun.modules.api.user.result.UserResult;
import com.pengshun.modules.api.user.service.UserService;
import com.pengshun.modules.common.AliYunSms;
import com.pengshun.modules.common.BaseResult;
import com.pengshun.modules.common.TokenUtil;
import com.pengshun.modules.common.UserType;
import com.pengshun.modules.domain.*;
import com.pengshun.modules.jwt.JwtTokenUtil;
import com.pengshun.modules.aliyun.SendMessage;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {


    private final RedisTemplate<String, String> redisTemplate;


    private final UserRepository userRepository;

    private final UserMapper userMapper;

    private final JwtTokenUtil util;

    private final UserWechatRepository userWechatRepository;

    private final MerchantRepository merchantRepository;
    private final MerchantMapper merchantMapper;

    private final SystemMapper systemMapper;

    private final PsUserInfoMapper psUserInfoMapper;

    private final IncomeRepository incomeRepository;

    private final MessageSource messageSource;

    private final HuanXinService  huanXinService;

    @Value("${need.code}")
    private Boolean needCode;

    @Override
    public BaseResult getCode(UserPara para) throws Exception {
        if (StringUtils.isBlank(para.getType())) {
            return new BaseResult(1, messageSource.getMessage("UserServiceImpl.getCode.getType", null, Locale.CHINA));
        }
        //调用短信接口发送短信
        int acode = (int) ((Math.random() * 9 + 1) * 1000);
        System.out.println("验证码：==========================" + acode);
        String code = acode + "";
        //成功保持验证码
        String typeCode = "";
        if (para.getType().equals("resgtion")) {
            String res = SendMessage.send(para.getPhone(), code, AliYunSms.RESGTION_CODE_TYPE);
            if (res != null && res.equals("OK")) {
                redisTemplate.delete(SystemPath.APP_RESGTION_CODE_PATH + para.getPhone());
                //设置有效期5分钟
                redisTemplate.boundValueOps(SystemPath.APP_RESGTION_CODE_PATH + para.getPhone()).set(code, 5, TimeUnit.MINUTES);
//                redisTemplate.opsForValue().set(SystemPath.APP_RESGTION_CODE_PATH + para.getPhone(),code,5, TimeUnit.MINUTES);
            }
        }
        if (para.getType().equals("login")) {
            String res = SendMessage.send(para.getPhone(), code, AliYunSms.LOGIN_CODE_TYPE);
            if (res != null && res.equals("OK")) {
                redisTemplate.delete(SystemPath.APP_LOGIN_CODE_PATH + para.getPhone());
                //设置有效期5分钟
                redisTemplate.boundValueOps(SystemPath.APP_LOGIN_CODE_PATH + para.getPhone()).set(code, 5, TimeUnit.MINUTES);
            }
        }
        if (para.getType().equals("forget")) {
            User user = userRepository.findByPhone(para.getPhone());
            if (user == null) {
                return new BaseResult(1, messageSource.getMessage("UserServiceImpl.getCode.error", null, Locale.CHINA));
            }
            String res = SendMessage.send(para.getPhone(), code, AliYunSms.FORGET_CODE_TYPE);
            if (res != null && res.equals("OK")) {
                redisTemplate.delete(SystemPath.APP_FORGET_CODE_PATH + para.getPhone());
                //设置有效期5分钟
                redisTemplate.boundValueOps(SystemPath.APP_FORGET_CODE_PATH + para.getPhone()).set(code, 5, TimeUnit.MINUTES);
            }
        }
        if (para.getType().equals("biding")) {
            String res = SendMessage.send(para.getPhone(), code, AliYunSms.BIDING_CODE_TYPE);
            if (res != null && res.equals("OK")) {
                redisTemplate.delete(SystemPath.APP_BIDING_CODE_PATH + para.getPhone());
                //设置有效期5分钟
                redisTemplate.boundValueOps(SystemPath.APP_BIDING_CODE_PATH + para.getPhone()).set(code, 5, TimeUnit.MINUTES);
            }
        }
        if (para.getType().equals("changePhone")) {
            String res = SendMessage.send(para.getPhone(), code, AliYunSms.CHANGE_PHONE_CODE_TYPE);
            if (res != null && res.equals("OK")) {
                redisTemplate.delete(SystemPath.APP_CHANGE_PHONE_CODE_PATH + para.getPhone());
                //设置有效期5分钟
                redisTemplate.boundValueOps(SystemPath.APP_CHANGE_PHONE_CODE_PATH + para.getPhone()).set(code, 5, TimeUnit.MINUTES);
            }
        }
        if (para.getType().equals("paypass")) {
            String res = SendMessage.send(para.getPhone(), code, AliYunSms.CHANGE_PAY_PASS_CODE_TYPE);
            if (res != null && res.equals("OK")) {
                redisTemplate.delete(SystemPath.APP_PAYPASS_CODE_PATH + para.getPhone());
                //设置有效期5分钟
                redisTemplate.boundValueOps(SystemPath.APP_PAYPASS_CODE_PATH + para.getPhone()).set(code, 5, TimeUnit.MINUTES);
            }
        }
        if (para.getType().equals("setpaypass")) {
            String res = SendMessage.send(para.getPhone(), code, AliYunSms.SET_PAY_PASS_CODE_TYPE);
            if (res != null && res.equals("OK")) {
            redisTemplate.delete(SystemPath.APP_PAYPASS_CODE_PATH + para.getPhone());
            //设置有效期5分钟
            redisTemplate.boundValueOps(SystemPath.APP_SETPAYPASS_CODE_PATH + para.getPhone()).set(code, 5, TimeUnit.MINUTES);
            }
        }

        return new BaseResult(0);
    }

    @Override
    public BaseResult verificationLogin(UserPara para) throws Exception {
        String code = (String) redisTemplate.boundValueOps(SystemPath.APP_LOGIN_CODE_PATH + para.getPhone()).get();
        if (code == null || !code.equals(para.getCode())) {
            return new BaseResult(1, messageSource.getMessage("UserServiceImpl.verificationLogin.code", null, Locale.CHINA));
        }
        User user = psUserInfoMapper.findUserByPhone(para.getPhone());
        if (user == null) {
            return new BaseResult(1, messageSource.getMessage("UserServiceImpl.verificationLogin.user", null, Locale.CHINA));
        }
        if (!user.getEnabled()) {
            //说明用户被禁用
            return new BaseResult(1, messageSource.getMessage("UserServiceImpl.verificationLogin.enabled", null, Locale.CHINA));
        }
        //更新别名 标签
        User user1 = userRepository.findById(user.getId()).orElseGet(User::new);
        updateoosTags(user1, para.getDeviceId());
        redisTemplate.delete(SystemPath.APP_LOGIN_CODE_PATH + para.getPhone());
        //存在token  先删除
        String token = util.generateToken(user);
        redisTemplate.delete(SystemPath.APP_TOKEN_PATH + user.getId());
        redisTemplate.opsForValue().set(SystemPath.APP_TOKEN_PATH + user.getId(), token, 30, TimeUnit.DAYS);


        UserResult result = new UserResult(user.getId(), token);
        return new BaseResult(0, result);
    }

    @Override
    public BaseResult updatePass(UserPara para) throws Exception {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String newPass = bCryptPasswordEncoder.encode(para.getNewPass());
        User user = psUserInfoMapper.findUserById(para.getId());
        if (!bCryptPasswordEncoder.matches(para.getOldPass(), user.getPassword())) {
            return new BaseResult(1, messageSource.getMessage("UserServiceImpl.updatePass.password", null, Locale.CHINA));
        }
        if (bCryptPasswordEncoder.matches(para.getNewPass(), user.getPassword())) {
            return new BaseResult(1, messageSource.getMessage("UserServiceImpl.updatePass.newPassword", null, Locale.CHINA));
        }
        user.setPassword(newPass);
        userRepository.save(user);
        return new BaseResult(0);
    }

    @Override
    public BaseResult passLogin(UserPara para) throws Exception {
        User user = psUserInfoMapper.findUserByPhone(para.getPhone());
        if (user == null) {
            return new BaseResult(1, messageSource.getMessage("UserServiceImpl.passLogin.user", null, Locale.CHINA));
        }
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        if (!bCryptPasswordEncoder.matches(para.getPass(), user.getPassword())) {
            return new BaseResult(1, messageSource.getMessage("UserServiceImpl.passLogin.password", null, Locale.CHINA));
        }
        if (!user.getEnabled()) {
            //说明用户被禁用
            return new BaseResult(1, messageSource.getMessage("UserServiceImpl.passLogin.users", null, Locale.CHINA));
        }
        //更新别名 标签
//        User user1 = userRepository.findById(user.getId()).orElseGet(User::new);
//        updateoosTags(user1, para.getDeviceId());
        //存在token  先删除
        String token = util.generateToken(user);
        System.err.println(token);
//        redisTemplate.delete(SystemPath.APP_TOKEN_PATH + user.getId());
//        redisTemplate.opsForValue().set(SystemPath.APP_TOKEN_PATH + user.getId(), token);
        redisTemplate.delete(SystemPath.APP_TOKEN_PATH + user.getId());
        redisTemplate.opsForValue().set(SystemPath.APP_TOKEN_PATH + user.getId(), token, 30, TimeUnit.DAYS);
        UserResult result = new UserResult(user.getId(), token);
        return new BaseResult(0, result);
    }

    @Override
    public UserDto findByName(String phone) {
        return userMapper.toDto(psUserInfoMapper.findUserByPhone(phone));
    }

    @Override
    public BaseResult resgtion(UserPara para) throws Exception {
        if(needCode) {
            String code = (String) redisTemplate.boundValueOps(SystemPath.APP_RESGTION_CODE_PATH + para.getPhone()).get();
            if (code == null || !code.equals(para.getCode())) {
                return new BaseResult(1, "未发送验证码或者验证码错误");
            }
        }
        User user = psUserInfoMapper.findUserByPhone(para.getPhone());
        if (user != null) {
            return new BaseResult(1, messageSource.getMessage("UserServiceImpl.resgtion.user", null, Locale.CHINA));
        }

        redisTemplate.delete(SystemPath.APP_RESGTION_CODE_PATH + para.getPhone());
        user = new User();
        user.setPhone(para.getPhone());
        user.setUserType(para.getUserType());
        user.setEnabled(true);
        user.setStatus(0);
        user.setUsername(para.getPhone());
        user.setCreateTime(new Date());
        //设置默认部门ID
        Dept dept = new Dept();
        dept.setId(1L);
        user.setDept(dept);
        user.setName("用户" + user.getPhone().substring(7, 11));
        user.setNickName("用户" + user.getPhone().substring(7, 11));
        user.setAvatarName("https://binmeitong.oss-cn-beijing.aliyuncs.com/authentication/202102021746555971");
        //创建用户
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        user.setPassword(bCryptPasswordEncoder.encode(para.getPass()));
        User u = userRepository.save(user);
        //设置标签  别名
        updateoosTags(u, para.getDeviceId());
        //创建用户余额账户表
        BigDecimal decimal = new BigDecimal(0);
        Income income = new Income(u.getId(), decimal, decimal, decimal, decimal,decimal,decimal);
        incomeRepository.save(income);
        //用户角色表添加数据
        if (user.getUserType().equals(UserType.THREE_STATUS) || user.getUserType().equals(UserType.FOUR_STATUS)) {
            UserRole role = new UserRole(u.getId(), user.getUserType().equals(UserType.THREE_STATUS) ? 6L : 7L);
            systemMapper.insertUserRole(role.getRoleId(), role.getUserId());
        }
        //绑定微信
        if(para.getOpenid()!=null){
            UserWechat wechat=userWechatRepository.findById(para.getOpenid()).orElseGet(UserWechat::new);
            wechat.setUserId(u.getId());
            userWechatRepository.save(wechat);
        }
        //存在token  先删除
        String token = util.generateToken(user);
        redisTemplate.boundValueOps(SystemPath.APP_TOKEN_PATH + user.getId()).set(token, 720, TimeUnit.HOURS);
        UserResult result = new UserResult(user.getId(), token);
        //注册环信 测试库不需要注册
        if(needCode) {
            huanXinService.resgtionUser(user.getId(), user.getNickName());
        }
        return new BaseResult(0, messageSource.getMessage("resgtion.success", null, Locale.CHINA));
    }

    @Override
    public BaseResult detil(Long id) {
        User user = userRepository.findById(id).orElseGet(User::new);
        if (user != null) {
            if (user.getUserType() == 0) {
                user.setMerchantName("普通用户");
            } else if (user.getUserType() == 1) {
                user.setMerchantName("司机");
            } else if (user.getUserType() == 2) {

                user.setMerchantName("车老板");
            }
            if (user.getUserType() == 3 && user.getMerchantName() == null) {
                user.setMerchantName("运输公司");
            }
            if (user.getUserType() == 4 && user.getMerchantName() == null) {
                user.setMerchantName("经销商");
            }
        }
        user.setPayPass(user.getPayPass() == null ? "0" : "1");
        return new BaseResult(0, user);
    }

    @Override
    public BaseResult forgetPass(UserPara para) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        User user = userRepository.findByPhone(para.getPhone());
        user.setPassword(bCryptPasswordEncoder.encode(para.getNewPass()));
        userRepository.save(user);
        return new BaseResult(0);
    }

    @Override
    public BaseResult wechatLogin(UserWechat para) {
        UserWechat wechat = userWechatRepository.findById(para.getOpenid()).orElseGet(UserWechat::new);
        if (wechat == null) {
            userWechatRepository.save(para);
        }
        if(wechat.getUserId()==null){
            //todo 说明没有绑定手机号  返回固定码 标识
        }
        String token = null;
        if (wechat.getUserId() != null) {
            //返回token
            User user = new User(wechat.getUserId());
            token = util.generateToken(user);
            redisTemplate.delete(SystemPath.APP_TOKEN_PATH + user.getId());
            redisTemplate.boundValueOps(SystemPath.APP_TOKEN_PATH + user.getId()).set(token, 720, TimeUnit.HOURS);
        }
        return new BaseResult(0, token, wechat);
    }

    @Override
    public BaseResult wechatBiding(UserPara para) {
        UserWechat wechat = userWechatRepository.findById(para.getOpenid()).orElseGet(UserWechat::new);
        if (wechat.getUserId() != null) {
            return new BaseResult(1, messageSource.getMessage("UserServiceImpl.wechatBiding.wechat", null, Locale.CHINA));
        }
        String code = (String) redisTemplate.boundValueOps(SystemPath.APP_BIDING_CODE_PATH + para.getPhone()).get();
        if (code == null || !code.equals(para.getCode())) {
            return new BaseResult(1, messageSource.getMessage("UserServiceImpl.wechatBiding.code", null, Locale.CHINA));
        }
        User user = psUserInfoMapper.findUserByPhone(para.getPhone());
        if (user == null) {
            return new BaseResult(1, messageSource.getMessage("UserServiceImpl.wechatBiding.user", null, Locale.CHINA));
        }
        if (!user.getEnabled()) {
            //说明用户被禁用
            return new BaseResult(1, messageSource.getMessage("UserServiceImpl.wechatBiding.enabled", null, Locale.CHINA));
        }
        redisTemplate.delete(SystemPath.APP_BIDING_CODE_PATH + para.getPhone());
        wechat.setUserId(user.getId());
        userWechatRepository.save(wechat);
        //更新token
        String token = util.generateToken(user);
        redisTemplate.delete(SystemPath.APP_TOKEN_PATH + user.getId());
        redisTemplate.boundValueOps(SystemPath.APP_TOKEN_PATH + user.getId()).set(token, 720, TimeUnit.HOURS);

        return new BaseResult(0, token, user);
    }

    private void updateoosTags(User user, String deviceId) throws Exception {
        String tagName = "";
        if (user.getUserType().equals(UserType.ZERO_STATUS)) {
            tagName = "binmeitongBuyUserTag";
        }
        if (user.getUserType().equals(UserType.ONE_STATUS)) {
            tagName = "binmeitongDriverTag";
        }
        if (user.getUserType().equals(UserType.TWO_STATUS)) {
            tagName = "binmeitongCarOwnerTag";
        }
        if (user.getUserType().equals(UserType.THREE_STATUS)) {
            tagName = "binmeitongTransportTag";
        }
        if (user.getUserType().equals(UserType.FOUR_STATUS)) {
            tagName = "binmeitongCoalMinerTag";
        }
        user.setTags(tagName);
        user.setAlias("binmeitongAlias" + user.getId());
        userRepository.save(user);
        //绑定别名
        OosPush.bindAlias(deviceId, user.getId());
        //绑定标签
        OosPush.bindTag(user.getId(), tagName);
    }

    @Override
    public BaseResult binuess(MerchantDto para) {
        //查询省市区code
        AddresDto city = systemMapper.selectBysdId(para.getAdcode());
        para.setScId(city.getCityId());
        para.setSpId(city.getProvinceId());
        merchantRepository.save(merchantMapper.toEntity(para));
        return new BaseResult(0);
    }

    @Override
    public BaseResult findByPhone(User para) {

        //当前搜索的用户  判断用户状态 和是否存在
        User user = userRepository.findByPhone(para.getPhone());
        if (user == null) {
            return new BaseResult(1, messageSource.getMessage("UserServiceImpl.findByPhone.user", null, Locale.CHINA));
        }

        if (user.getStatus() != 2) {
            //未通过认证审核
            return new BaseResult(1, messageSource.getMessage("UserServiceImpl.findByPhone.getUserType", null, Locale.CHINA));
        }

        //查询当前操作人信息
        User opetoredUser = userRepository.findById(para.getId()).orElseGet(User::new);
        if (opetoredUser.getUserType().equals(UserType.ONE_STATUS)) {
            //操作人是司机时候 只能搜索车主
            if (!user.getUserType().equals(UserType.TWO_STATUS) && !user.getUserType().equals(UserType.THREE_STATUS)) {
                //说明该用户不是车主
                return new BaseResult(1, messageSource.getMessage("UserServiceImpl.findByPhone.notcarboss", null, Locale.CHINA));
            }
        } else {
            //操作人是车主时候  只能搜索司机
            if (!user.getUserType().equals(UserType.ONE_STATUS)) {
                //说明该用户不是司机
                return new BaseResult(1, messageSource.getMessage("UserServiceImpl.findByPhone.notdriver", null, Locale.CHINA));
            }
        }
        String contractContent = "";
        //查询合同信息
        PsContractDetil detil = psUserInfoMapper.getContractDetil();
        if (detil != null) {
            contractContent = detil.getContent()
                    .replace("applyCard", opetoredUser.getIdcard().substring(0, 5) + "******" + opetoredUser.getIdcard().substring(15, 18))
                    .replace("agreeCard", user.getIdcard().substring(0, 5) + "******" + user.getIdcard().substring(15, 18))
                    .replace("applyName", opetoredUser.getName().substring(0, 1) + "*")
                    .replace("agreeName", user.getName().substring(0, 1) + "*");
        }
        //查询合同须知
        PsContractKnow know = psUserInfoMapper.getContractKnow();
        UserDto dto = userMapper.toDto(user);
        dto.setContractKnow(know.getContent());
        dto.setContractDetil(contractContent);
        return new BaseResult(0, dto);
    }

    @Override
    public BaseResult getCenter() {
        Long userId = TokenUtil.getTokenUserId();
        Integer userType = null;
        if (userId == null) {
            userType = 0;
        } else {
            userType = userRepository.findById(userId).orElseGet(User::new).getUserType();
        }
        List<UserCenter> list = psUserInfoMapper.selectUserCenterByType(userType);
        List<UserCenter> centerList = new ArrayList<>();
        for (UserCenter center : list) {
            if (center.getParentId() == null) {
                centerList.add(center);
            }
        }
        for (UserCenter center : centerList) {
            List<UserCenter> centens = new ArrayList<>();
            for (UserCenter cet : list) {
                if (cet.getParentId() != null && center.getUserCenterId().longValue() == cet.getParentId()) {
                    centens.add(cet);
                }
            }
            center.setCenters(centens);
        }
        return new BaseResult(0, centerList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult change(UserPara para) {
        User user = psUserInfoMapper.findUserById(para.getId());
        if (user.getStatus() == 1 || user.getStatus() == 2) {
            return new BaseResult(0, messageSource.getMessage("UserServiceImpl.change.getStatus", null, Locale.CHINA));
        }
        user.setStatus(0);
        user.setUserType(para.getUserType());
        userRepository.save(user);
        //删除认证信息
        systemMapper.deleteCitizenByUserId(para.getId());
        //删除司机表信息
        systemMapper.deleteDrivingLicenseByUserId(para.getId());
        //删除商户表信息
        systemMapper.deleteMerchantByUserId(para.getId());
        //用户角色表添加数据
        //先删除 在添加
        systemMapper.deleteUserRole(user.getId());
        if (user.getUserType().equals(UserType.THREE_STATUS) || user.getUserType().equals(UserType.FOUR_STATUS)) {
            UserRole role = new UserRole(user.getId(), user.getUserType().equals(UserType.THREE_STATUS) ? 6L : 7L);
            systemMapper.insertUserRole(role.getRoleId(), role.getUserId());
        }

        return new BaseResult(0);
    }

    @Override
    public BaseResult changePhone(UserPara para) {
        //修改手机号
        String code = (String) redisTemplate.boundValueOps(SystemPath.APP_CHANGE_PHONE_CODE_PATH + para.getPhone()).get();
        if (code == null || !code.equals(para.getCode())) {
            return new BaseResult(1, messageSource.getMessage("UserServiceImpl.changePhone.code", null, Locale.CHINA));
        }
        redisTemplate.delete(SystemPath.APP_CHANGE_PHONE_CODE_PATH + para.getPhone());
        User user = psUserInfoMapper.findUserByPhone(para.getPhone());
        if (user != null) {
            return new BaseResult(1, messageSource.getMessage("UserServiceImpl.changePhone.user", null, Locale.CHINA));
        }
        User oldUser = userRepository.findById(para.getId()).orElseGet(User::new);
        oldUser.setPhone(para.getPhone());
        userRepository.save(oldUser);
        return new BaseResult(0, messageSource.getMessage("update.success", null, Locale.CHINA));
    }

    @Override
    public BaseResult update(UserPara user) {
        User user1 = userRepository.findById(user.getId()).orElseGet(User::new);
        //修改头像
        if(user.getAvatarName()!=null&&!StringUtils.EMPTY.equals(user.getAvatarName())){
            user1.setAvatarName(user.getAvatarName());
        }
        //修改昵称
        if(user.getNickName()!=null&&!StringUtils.EMPTY.equals(user.getNickName())){
            user1.setNickName(user.getNickName());
        }
        userRepository.save(user1);
        return new BaseResult(0, messageSource.getMessage("update.success", null, Locale.CHINA));
//        if (user.getOldPayPass() != null && user1.getPayPass() == null) {
//            return new BaseResult(1, messageSource.getMessage("UserServiceImpl.update.bCryptPasswordEncoder", null, Locale.CHINA));
//        }
//        if (user.getOldPayPass() != null || user.getPayPass() != null) {
//            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//            if (user.getOldPayPass() != null) {
//                //说明是修改支付密码
//                if (!bCryptPasswordEncoder.matches(user.getOldPayPass(), user1.getPayPass())) {
//                    return new BaseResult(1, messageSource.getMessage("UserServiceImpl.update.getPayPass", null, Locale.CHINA));
//                }
//                if (bCryptPasswordEncoder.matches(user.getOldPayPass(), user1.getPayPass())) {
//                    return new BaseResult(1, messageSource.getMessage("UserServiceImpl.update.user", null, Locale.CHINA));
//                }
//
//            }
//            user1.setPayPass(bCryptPasswordEncoder.encode(user.getPayPass()));
//        }
    }

    @Override
    public BaseResult setPayPass(UserPara para) {
        User user = userRepository.findById(para.getId()).orElseGet(User::new);
        if (user.getPayPass() != null) {
            return new BaseResult(1, "支付密码已经设置过了！");
        }
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        user.setPayPass(bCryptPasswordEncoder.encode(para.getPayPass()));
        userRepository.save(user);
        return new BaseResult(0, messageSource.getMessage("set.success", null, Locale.CHINA));
    }

    @Override
    public BaseResult updatePayPass(UserPara para) {
        User user = userRepository.findById(para.getId()).orElseGet(User::new);
        if (user.getPayPass() == null) {
            return new BaseResult(1, messageSource.getMessage("UserServiceImpl.setPayPass.getPayPass", null, Locale.CHINA));
        }
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

        if (para.getType().equals("1")) {
            //说明是修改支付密码
            if (!bCryptPasswordEncoder.matches(para.getOldPayPass(), user.getPayPass())) {
                return new BaseResult(1, messageSource.getMessage("UserServiceImpl.setPayPass.bCryptPasswordEncoder", null, Locale.CHINA));
            }
            if (bCryptPasswordEncoder.matches(para.getPayPass(), user.getPayPass())) {
                return new BaseResult(1, messageSource.getMessage("UserServiceImpl.setPayPass.payPass", null, Locale.CHINA));
            }

        }
        String newPass = bCryptPasswordEncoder.encode(para.getPayPass());
        user.setPayPass(newPass);
        userRepository.save(user);
        return new BaseResult(0, messageSource.getMessage("update.success", null, Locale.CHINA));
    }

    @Override
    public BaseResult verifyCode(UserPara para) {
        //忘记密码传(forget)  更换手机号传changePhone 更改支付密码传paypass 设置支付密码 setpayass
        if (para.getType().equals("paypass")) {
            // 修改支付密码验证
            String code = (String) redisTemplate.boundValueOps(SystemPath.APP_PAYPASS_CODE_PATH + para.getPhone()).get();
            if (code == null || !code.equals(para.getCode())) {
                return new BaseResult(1, messageSource.getMessage("UserServiceImpl.setPayPass.code", null, Locale.CHINA));
            }
            redisTemplate.delete(SystemPath.APP_PAYPASS_CODE_PATH + para.getPhone());
        }
        if (para.getType().equals("forget")) {
            //忘记密码
            String code = (String) redisTemplate.boundValueOps(SystemPath.APP_FORGET_CODE_PATH + para.getPhone()).get();
            if (code == null || !code.equals(para.getCode())) {
                return new BaseResult(1, messageSource.getMessage("UserServiceImpl.forgetPass.code", null, Locale.CHINA));
            }
            redisTemplate.delete(SystemPath.APP_FORGET_CODE_PATH + para.getPhone());
        }
        if (para.getType().equals("changePhone")) {

        }
        if (para.getType().equals("setpayass")) {
            String code = (String) redisTemplate.boundValueOps(SystemPath.APP_SETPAYPASS_CODE_PATH + para.getPhone()).get();
            if (code == null || !code.equals(para.getCode())) {
                return new BaseResult(1, messageSource.getMessage("UserServiceImpl.setPayPass.code", null, Locale.CHINA));
            }
            redisTemplate.delete(SystemPath.APP_SETPAYPASS_CODE_PATH + para.getPhone());
        }

        return new BaseResult(0);
    }

    @Override
    public BaseResult getRoll() {
        List<UserDto> userList = psUserInfoMapper.findRoolUsers();
        for (UserDto dto : userList) {
            dto.setRolls("用户" + dto.getPhone().substring(0, 3) + "****" + dto.getPhone().substring(7, 11) + "注册成功");
            if(dto.getUserType()==3||dto.getUserType()==4){
                dto.setRolls("企业" + dto.getPhone().substring(0, 3) + "****" + dto.getPhone().substring(7, 11) + "入驻成功");
            }
        }
        return new BaseResult(0, userList);
    }


}
